
//所有可点击页面
let alist=[];
let alist_index=0;
let list=[]
const config={
	server:localStorage.getItem('server')?localStorage.getItem('server'):"http://162.14.113.45:8708",//后台服务地址
	serverPath:'',//当前服务器目录前缀
	getlist:false,//是否开始上传
	alist_erro:0,//错误计数
	alist_max:3,//最大错误尝试次数
	pathHead:'',//选中的文件目录前缀
}
const httpdata={
	createDirectory:(data)=>{return http(`${config.server}/index/createDirectory`,data)},//创建文件/子文件夹｛directoryName文件名称， folderPath目录地址｝
	fileList:(data)=>{return http(`${config.server}/index/fileList`,data)},//获取指定目录下文件列表｛folderPath目录地址｝
	fileUpload:()=>{return `${config.server}/index/fileUpload`},//文件上传｛directoryPath文件地址，file文件名称｝
	renameDirectory:(data)=>{return http(`${config.server}/index/renameDirectory`,data)},//重命名文件夹｛folderPath目录地址，newName新文件名称，oldName旧文件名称｝
}
function http(url,data){
	return new Promise((resolve, reject)=>{
		$.post(url,data,function(data,status,xhr){
			if(status=='success')resolve(data)
			else reject(data)
		});
	})
}
function downURL(url,callback){
	let name=url.split('/').pop();
	fetch(url).then((response) => {
	  const reader = response.body.getReader();
	  let list;
	  let urlOBJ=new URL(url)
	  
	  //预览时有个沙雕机制，生成时间随机前缀
	  let pathnamearr=urlOBJ.pathname.split('/')[1]
	  if(pathnamearr.split('.').length==3){
		  urlOBJ.pathname=urlOBJ.pathname.replace('/'+pathnamearr,'')
	  }
	  
	  let pathname=config.pathHead+decodeURI(urlOBJ.pathname)
	  let namearr=pathname.split('/')
	  namearr.pop()
	  pathname=namearr.join('/')
	  const stream = new ReadableStream({
	    start(controller) {
	      // 下面的函数处理每个数据块
	      let push = () => {
	        // "done"是一个布尔型，"value"是一个Unit8Array
	        reader.read().then(({done, value}) => {
	          // 判断是否还有可读的数据？
	          if (done) {
	            // 告诉浏览器已经结束数据发送。
	            let uintList = new Uint8Array(list);
	            var blob = new Blob([uintList]);
	            // 1、转为file
	            let files = new window.File([blob], name);
				files.filepath=pathname
	            let fd = new FormData();
	            fd.append('directoryPath', pathname);
	            fd.append('file', files);
				$.ajax({
					type:'post',
					data: fd,
					contentType : false, 
					processData : false,
					url:httpdata.fileUpload(),
					success : function(data) {
						console.log(data)
						callback&&callback(true,'')
					},
					error:function(data) {
						callback&&callback('',true)
					},
				}); 
	
	            controller.close();
	            return;
	          }
	
	          if (!list) {
	            list = Array.from(value);
	          } else {
	            list = list.concat(Array.from(value));
	          }
	
	          // 取得数据并将它通过controller发送给浏览器。
	          controller.enqueue(value);
	          push();
	        });
	      };
	
	      push();
	    }
	  });
	
	  return new Response(stream, {headers: {'Content-Type': 'text/html'}});
	});
}
(function() {
	console.log('启动成功');//获取页面所有请求资源
	list = getList(window.performance.getEntriesByType("resource"));
	list.push(decodeURI(location.origin+location.pathname))
	list.push(decodeURI(location.origin+'/index.html'))
	list.push(decodeURI(location.origin+'/start.html'))
	list.push(decodeURI(location.origin+'/resources/scripts/prototypePost.js'))
	list.push(decodeURI(location.origin+'/resources/scripts/messagecenter.js'))
	list.push(decodeURI(location.origin+'/resources/expand.html'))
	document.getElementById('expandFrame').onload=function(){
		let inFrameList =getList(expandFrame.performance.getEntriesByType("resource"));
		inFrameList.push(decodeURI(expandFrame.location.origin+expandFrame.location.pathname))
		list=list.concat(inFrameList)
	}
	document.getElementById('mainFrame').onload=function(){
		let inFrameList =getList(mainFrame.performance.getEntriesByType("resource"));
		inFrameList.push(decodeURI(mainFrame.location.origin+mainFrame.location.pathname))
		list=list.concat(inFrameList)
		config.getlist&&toPage()
	}
})();
//循环遍历子页面
function toPage(){
	upfile.text(`查询页面${alist_index}/${alist.length}`)
	if(alist_index<alist.length){
		alist[alist_index++].click()
		let inFrameList =getList(mainFrame.performance.getEntriesByType("resource"));
	}else{
		upfile.text(`查询页面${alist_index+1}/${alist.length}`)
		list = [...new Set(list)].sort();
		config.getlist=false;
		//list=list.splice(1)
		console.log('开始')
		send()
	}
}
//获取页面资源列表
function getList(performance){
	let list=performance.map(v=>decodeURI(v.name));
	list = [...new Set(list)].sort();
	let datajsarr=list.filter(v=>{return /data.js$/.test(v)})
	if(datajsarr[0]){
		getdatajs(datajsarr[0])
	}
	return list
}
//遍历子页面data.js中资源表
function getdatajs(url){
	let strleng;
	fetch(url).then(v=>{
		return v.text()
	}).then(v=>{
		strleng=v.match(/images\/.*?"/g)
		strleng=strleng.map(s=>{
			return location.origin+'/'+s.replace("\"","")
		})
		list = list.concat(strleng)
		list = [...new Set(list)].sort()
	})
}
function send(i=0){
	upfile.text(`上传资源${i}/${list.length}`)
	if(i==list.length){
		console.log('上传结束')
		upprd.hide();
		let str=getPath()
		str=str.split('/').splice(3).join('/')
		str=`https://${str}/index.html`
		urlshow.val(str)
		enddiv.show();
		return;
	}
	downURL(list[i],(d,e)=>{
		console.log(`上传第${i+1}条数据${d?'成功':'重试'}：${list[i]}`)
		if(d){
			config.alist_erro=0;
			send(++i)
		}else{
			if(++config.alist_erro==config.alist_max){
				send(++i)
			}else{
				send(i)
			}
		}
	})
	
}
